package cn.com.bluemoon.daps.webhook.controller;


import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.common.webhook.WebhookClient;
import cn.com.bluemoon.daps.common.webhook.WechatWebhookDto;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * <p>
 * webhook 前端控制器
 * </p>
 *
 * @author admin
 * @since 2020-08-04
 */
@RestController
@Slf4j
@RequestMapping("/api")
public class WebhookController {

    @GetMapping(value = "/test0")
    public String test0(HttpServletRequest request) {
        ThreadLocal<Byte[]> localVariable = new ThreadLocal<Byte[]>();
        localVariable.set(new Byte[4096 * 1024]);// 为线程添加变量
        return "success";
    }

    /**
     * @param map  http://gitlab.admin.bluemoon.com.cn/help/user/project/integrations/webhooks
     * @param type
     * @return
     */
    @PostMapping(value = "/webhook")
    public ResultBean<String> ok(@RequestBody Map<String, Object> map,
                                 @RequestParam(value = "type", defaultValue = "1") Integer type,
                                 @RequestParam(value = "gitRefRegex", required = false) String gitRefRegex) {
        log.info("accept :{}", map);
        // 增加入参 指定哪个分支才推送
        String gitRef = Objects.toString(map.getOrDefault("ref", null), "");
        if (StringUtils.isNotBlank(gitRefRegex) && !Pattern.matches(gitRefRegex, gitRef)) {
//            Pattern.matches(".*/master", "refs/head/master")
            return ResultBean.ok(StrUtil.format("请求结束，当前推送信息的分支[{}]不符合推送规则[{}]", gitRef, gitRefRegex));
        } else {
            log.info("当前请求分支{}符合规则{}，开启发送到webhook...", gitRef, gitRefRegex);
        }
        String msgType = type == 1 ? WechatWebhookDto.NEWS_MSG_TYPE : WechatWebhookDto.MARKDOWN_MSG_TYPE;
        String reqBody = WebhookClient.getWechatWebhookGitlabReqBody(map, msgType);
        if (reqBody == null) {
            return ResultBean.error("nothing");
        }
        HttpRequest post = HttpRequest.post(WebhookClient.WECHAR_WEBHOOK_URL);
        post.body(reqBody, "application/json");
        try (HttpResponse response = post.execute()) {
            String body = response.body();
            log.info("resp:{}, status:{}", body, response.getStatus());
            return ResultBean.ok(response.getStatus() + ",msg:")
                    .addMoreData("requestBody", map);
        }
    }
}
